package com.magic.gre.behavior;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Scroller;

import com.magic.gre.R;

/**
 * Title Behavior
 */
public class XiamiTitleBehavior extends CoordinatorLayout.Behavior<View> {

    private Context mContext;
    private Scroller mScroller;
    private ScrollerRunnable mScrollRunnable;
    private View mChildView;
    private Float mHeight=0F;
    public XiamiTitleBehavior() {

    }

    public XiamiTitleBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScroller=new Scroller(context);
        mContext = context;
    }

    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull View child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
        this.mChildView=child;
        return super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type);
    }

    @Override
    public boolean onLayoutChild(CoordinatorLayout parent, View child, int layoutDirection) {
        return super.onLayoutChild(parent, child, layoutDirection);
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
        return isDependOn(dependency);
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
        float y = -(1 - dependency.getTranslationY() / getHeaderOffset()) * getTitleHeight();
        child.setY(y);
        return true;
    }

    private int getHeaderOffset() {
        return mContext.getResources().getDimensionPixelOffset(R.dimen.header_offset);
    }

    private int getTitleHeight() {
        return mContext.getResources().getDimensionPixelOffset(R.dimen.xiami_title_height);
    }

    private boolean isDependOn(View dependency) {
        return dependency != null && dependency.getId() == R.id.header;
    }

    private void createRunnable(){
        if (mScrollRunnable==null){
            mScrollRunnable=new ScrollerRunnable(mScroller,mChildView,getTitleHeight());
        }
    }

    public void scrollToOpen(){
        createRunnable();
        mScrollRunnable.scrollToOpen();
    }
}
